package org.goldfish.message_board01.filters;

import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class DecryptionFilter extends HttpFilter {
    private static final int[] shiftKey = {1, 2, 3, 5, 4};

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化配置（如果需要）
    }

    @Override
    public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String path = request.getServletPath();
        if (path.contains("js") || path.contains("css") || path.contains("images")) {
            chain.doFilter(request, response);
            return;
        }
        if (!(path.equals("/") || path.equals("/register"))) {
            chain.doFilter(request, response);
            return;
        }
        Map<String, String[]> parameterMap = new HashMap<>(request.getParameterMap());
        String name_raw = request.getParameter("username");
        String pass_raw = request.getParameter("password");

        // 对用户名和密码字段解密
        parameterMap.forEach((key, values) -> {
            if ("username".equals(key) || "password".equals(key)) {
                for (int i = 0; i < values.length; i++) {
                    values[i] = caesarDecrypt(values[i]);
                }
            }
        });
        try {
            request.setAttribute("username", parameterMap.get("username")[0]);
            request.setAttribute("password", parameterMap.get("password")[0]);
        } catch (RuntimeException ignored) {

        }
        chain.doFilter(request, response);
        if (path.equals("/") && request.getMethod().equalsIgnoreCase("POST") && "on".equals(request.getParameter("rememberMe"))) {
            Cookie usernameCookie = new Cookie("username", name_raw);
            Cookie passwordCookie = new Cookie("password", pass_raw);

            // 设置路径，使其适用于整个应用程序
            usernameCookie.setPath("/");
            passwordCookie.setPath("/");

            // 设置安全标志（如果适用）
            usernameCookie.setHttpOnly(true);
            passwordCookie.setHttpOnly(true);

            // 设置有效期为 7 天
            usernameCookie.setMaxAge(7 * 24 * 60 * 60);
            passwordCookie.setMaxAge(7 * 24 * 60 * 60);

            // 添加 Cookie
            response.addCookie(usernameCookie);
            response.addCookie(passwordCookie);
        }


    }

    private String caesarDecrypt(String text) {
        StringBuilder decryptedText = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            int shift = shiftKey[i % shiftKey.length];
            char charCode = text.charAt(i);
            charCode = (char) (charCode - shift);
            decryptedText.append(charCode);


        }
        return decryptedText.toString();
    }

    @Override
    public void destroy() {
        // 清理资源（如果需要）
    }
}
